import axios from "axios";
import { useRouter } from "vue-router";

export function request(config) {
  const router = useRouter();
  const instance = axios.create({
    // baseURL: "http://admin.ouyangke.cn/index.php/api/",
    baseURL: "http://www.tp.com/index.php/api/",
    timeout: 5000,
  });
  //请求拦截
  instance.interceptors.request.use(
    (config) => {
      config.headers['token'] = localStorage.getItem('token');
      return config;
    },
    (err) => {
      console.log('请求错误', err);
    }
  );
  //响应拦截
  instance.interceptors.response.use(
    (res) => {
      console.log('res',res);
      if (res.data.code !== 1 && config.msg) {
        alert(res.data.message)
      }
      return res.data?.data
    },
    (err) => {
      console.log('响应错误', err);
      // 如果没有授权， 去login
      if (err.response.data.message === 'token验证错误') {
        router.push('/login')
        alert('用户信息失效，请重新登录')
      }
    }
  );
  return instance(config);
}